package com.keeson.android_cli.ui;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gyf.immersionbar.ImmersionBar;
import com.keeson.android_cli.R;
import com.keeson.android_cli.base.BaseActivity;
import com.keeson.android_cli.base.BaseEvent;
import com.keeson.android_cli.util.CustomToast;
import com.keeson.android_cli.util.LogUtils;
import com.keeson.android_cli.util.StatusBarUtil;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by jiaqiZHou
 * on 2020/12/4
 */
public class WebActivity extends BaseActivity {
    public String TAG = getClass().getSimpleName();
    public long time = 0;

    @BindView(R.id.fake_status_bar)
    View mFakeStatusBar;
    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.web_content)
    WebView webContent;

    private String url;
    private String content;
    private String title;

    @Override
    public void beforeShow(Bundle savedInstanceState) {
        super.beforeShow(savedInstanceState);
        Intent intent = getIntent();
        if (intent == null) {
            CustomToast.INSTANCE.showToast(context,"no_url");
        } else {
            url = intent.getStringExtra("url");
            content = intent.getStringExtra("content");
            title = intent.getStringExtra("title");

        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {
        mFakeStatusBar = findViewById(R.id.fake_status_bar);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mFakeStatusBar.getLayoutParams();
        layoutParams.topMargin = StatusBarUtil.getStatusBarHeight(context);
        tv_title.setText(title);

        WebSettings settings = webContent.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSavePassword(true);
        settings.setSaveFormData(true);
        settings.setDatabaseEnabled(true);
        settings.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
        settings.setBuiltInZoomControls(true);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setMediaPlaybackRequiresUserGesture(false);
        if (Build.VERSION.SDK_INT >= 21) {
            settings.setMixedContentMode(2);
        }

        webContent.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
//                super.onReceivedSslError(webView, sslErrorHandler, sslError);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                LogUtils.i("onPageStarted start url is >> " + url);
//                if (!isAllowRefreshPage(url)) {
//                    smartRefreshLayout.setEnableRefresh(false);
//                } else {
//                    smartRefreshLayout.setEnableRefresh(true);
//                }
                super.onPageStarted(view, url, favicon);
                time = System.currentTimeMillis();
//                Log.i(TAG,"onPageStarted : "+ time+"is X5" + App.isX5Core());
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "onPageStarted : use time ms " + (System.currentTimeMillis() - time));
                LogUtils.i("onPageFinished finish url is >>" + url);
//                LogUtil.i("isNetPrepare ? " + isNetPrepare);

            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                LogUtils.i("onReceivedError >> " + error.getErrorCode() + error.getDescription());
                LogUtils.i("onReceivedError uri " + request.getUrl());
//                setErrorRecode(request.getUrl());
//                if (!LOCAL_ERROR_PAGE.equals(webContent.getOriginalUrl())) {
//                    webContent.loadUrl(LOCAL_ERROR_PAGE);
//                }
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
                LogUtils.i("onReceivedHttpError>>" + webResourceResponse.getStatusCode());
                super.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(final WebView view, WebResourceRequest request) {
                LogUtils.i("shouldInterceptRequest>>");
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("taobao://") || url.contains(".taobao.com")) {
                    return openTaobaoShopping(url);
                    // return true
                }
                if (url.contains("openapp.jdmobile://")) {
                    return openJindongShopping(url);
                    // return true
                }
                if (url.contains("pinduoduo://")) {
                    openPinduoduoShopping(url);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        webContent.addJavascriptInterface(new Receiver(), "JsCall");

        if (!TextUtils.isEmpty(url)) {
            webContent.loadUrl("file:///android_asset/dist/index.html");//
        } else {
            try {
//                webContent.loadData(content, "text/html",  "UTF-8");
                webContent.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    class Receiver {
        @JavascriptInterface
        public void center() {
            LogUtils.e("center come in");
            finish();
        }

        @JavascriptInterface
        public void iOSGetValue() {
            LogUtils.e("iOSGetValue");
            finish();
        }
    }

    private boolean openJindongShopping(String url) {
        if (checkPackage(WebActivity.this, "com.jingdong.app.mall")) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            return true;
        } else {
            return true;
        }
    }
    private boolean openTaobaoShopping(String url){
        if (checkPackage(WebActivity.this, "com.taobao.taobao")) {
            String turl = url;
            if (turl.contains("https")) {
                turl = turl.replace("https", "taobao");
            }
            if (turl.contains("http")) {
                turl = turl.replace("http", "taobao");
            }

            Intent taobao = new Intent();
            taobao.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse(turl);
            taobao.setData(uri);
            startActivity(taobao);
            return true;
        } else {
            return false;
        }
    }

    private void openPinduoduoShopping(String url) {
        if (checkPackage(this, "com.xunmeng.pinduoduo")) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse(url);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(uri);
            startActivity(intent);
        }
    }

    public static boolean checkPackage(Context context , String packageName)
    {
        if (packageName == null || "".equals(packageName))
            return false;
        try{
            context.getPackageManager().getApplicationInfo(packageName, PackageManager
                    .GET_UNINSTALLED_PACKAGES);
            return true;
        }catch (PackageManager.NameNotFoundException e){
            return false;
        }

    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(BaseEvent event) {
        switch (event.getCode()) {

        }
    }


    @OnClick({R.id.iv_back})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                    finish();
                break;
        }
    }



    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)
                .statusBarDarkFont(true)//状态栏黑色
                .barColor(R.color.white)
                .navigationBarColor(R.color.color_F5F5F5)
                .init();
    }

}